package pers.vic.test;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import pers.vic.boot.base.tool.Tools;
import pers.vic.boot.util.thread.CustomThreadFactory;
import pers.vic.test.redis.subscribe.impl.TestRedisSubscribe;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.time.LocalTime;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Test  启动类
 * @author Vic.xu
 */
@SpringBootApplication(/*exclude = SecurityAutoConfiguration.class*/) // (scanBasePackages = "pers.vic.test")
@EnableCaching
@EnableScheduling
@RestController
@MapperScan(basePackages = "pers.vic.test.**.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
//@ServletComponentScan
//@Configuration
public class BootWebTestApplication {

    private Logger logger = LoggerFactory.getLogger(BootWebTestApplication.class);

    public static void main(String[] args) {
        try {
            /*
             * The valid characters are defined in RFC 7230 and RFC 3986
             * 修改$TOMCAT_HOME/conf/catalina.properties，添加属性 tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}
             */
            //System.setProperty("tomcat.util.http.parser.HttpParser.requestTargetAllow", "|{}:\"");
            //System.setProperty("spring.devtools.restart.enabled", "false");
            ConfigurableApplicationContext context = SpringApplication.run(BootWebTestApplication.class, args);
            DataSource dataSource = context.getBean(DataSource.class);
            System.out.println("DataSource:      " + dataSource);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private Collection<SqlSessionFactory> sessionFactories;


    @GetMapping({"", "/"})
    public String index(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        sb.append("\n").append("").append(request.getScheme()).append("://").append(request.getServerName()).append(":")
                .append(request.getServerPort()).append(request.getContextPath());

        return "welcome to index " + sb;
    }

    @GetMapping({"/test/p"})
    @ResponseBody
    public String p(String param, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("...........................................................param:" + param);
        Tools.writeJson(LocalTime.now(), response);
        return param + LocalTime.now();
    }

    @Autowired
    TestRedisSubscribe testRedisSubscribe;

    @Value("${test.dec}")
    private String dec;

    @PostConstruct
    public void post() throws InterruptedException {

        logger.info("sessionFactories size: {}......" + sessionFactories.size());
        logger.info("dec = " + dec);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                1, 1, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100), new CustomThreadFactory("BootWebTestApplication"));
        poolExecutor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println("post....testRedisSubscribe.publish " + i);
                testRedisSubscribe.publish(LocalTime.now() + "  " + i);
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

    }

}
